<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminUsers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Admin\ToolsController;
use Log;
use Carbon\Carbon;

class AdminController extends Controller
{
    public function index(Request $request){
        $adminusers = DB::table('admin_users')->paginate(PAGE_NUM);
          /*这是搜索啊*/
          if(isset($_GET['table_search']))
          {
            $mark = $_GET['table_search'];
            if(is_numeric($mark))
            {
              $adminusers = DB::table('admin_users')
                            ->where('username','like',"%$mark%")
                            ->paginate(10);
          $url=url('admin/adminuser');
          $adminusers->withPath($url.'?table_search='.$mark);
            }
            if(preg_match("/[\x7f-\xff]/", $mark))//正则表达式判断是否有汉字字符
            {
              $adminusers = DB::table('admin_users')
                            ->where('username','like',"%$mark%")
                            ->paginate(10);
              $url=url('admin/adminuser');
              $adminusers->withPath($url.'?table_search='.$mark);
            }
            if(preg_match ("/^[A-Za-z]/", $mark)){
            $adminusers = DB::table('admin_users')
                          ->where('username','like',"%$mark%")
                          ->paginate(10);
                  $url=url('admin/adminuser');
                  $adminusers->withPath($url.'?table_search='.$mark);
            }
          }
        return view('admin.admin.index', compact('adminusers','mark'));
    }

    public function show($id){
        $admin = AdminUsers::with('roles.perms')->find($id);
        $roles = Role::get();
        return view('admin.admin.show', compact('admin', 'roles'));
    }

    public function create(){
        return view('admin.admin.create');
    }

    public function store(Requests\CreateAdminUsersRequest $request){
      if(preg_match("/[\x7f-\xff]/", $request->username)){
        exit(json_encode(array('code'=>0,'msg'=>'用户名不能出现中文')));
      }else{
        $this->validate($request, [
          'username' => 'required|unique:admin_users,name',
          'name'     => 'required|alpha',
          'email'    => 'email'
        ],['alpha'=>':attribute 只能由汉字和字母组成'],['name'=>'姓名']);
        $data = $request->all();
        $unword = $data['password'];
        $data['password'] = bcrypt($data['password']);
        $data['login_ip'] = $request->getClientIp();
        $data['name'] = trim(str_replace(" ","",$data['name'])," ");
        $result = AdminUsers::create($data);
        if ($result){
          exit(json_encode(array('code'=>1, 'url'=>'/admin/adminuser')));
        }else{
          exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
      }
    }

    public function edit($id){
        $admin = AdminUsers::findOrFail($id);
        return view('admin.admin.edit', compact('admin'));
    }

    public function update(Requests\CreateAdminUsersRequest $request, $id){
      if(preg_match("/[\x7f-\xff]/", $request->username)){
        exit(json_encode(array('code'=>0,'msg'=>'用户名不能出现中文')));
      }
      $this->validate($request, [
        'username' => 'required',
        'name'     => 'required|alpha',
        'email'    => 'email'
      ],['alpha'=>':attribute 只能由汉字和字母组成'],['name'=>'姓名']);
        $admin = AdminUsers::findOrFail($id);
        $data = $request->all();
        unset($data['username']);
        if ($data['password'] == null){
            unset($data['password']);
        }else{
            $data['password'] = bcrypt($data['password']);
        }
        $data['name'] = trim(str_replace(" ","",$data['name'])," ");
        $result = $admin->update($data);
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/adminuser')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function destroy($id){
        $admin = AdminUsers::findOrFail($id);
        if ($admin->delete()){
            exit(json_encode(array('code'=>1)));
        } else {
            exit(json_encode(array('code'=>0)));
        }
    }

    public function roleAdd(Request $request, $id){
        $admin = AdminUsers::findOrFail($id);
        if ($roleArr = $request->role){
            $admin->roles()->sync($roleArr);
        }else{
            $admin-roles()->detach();
        }
        exit(json_encode(['code'=>1, 'url'=>'/admin/adminuser/'.$id]));
    }

    public function getLogs(Request $request){
        if (isset($_GET['table_search'])){
          $mark = $_GET['table_search'];
            $logs = DB::table('admin_logs')
                ->join('admin_users','admin_logs.admin_id','=','admin_users.id')
                ->where('username', 'like', '%'.$mark.'%')
                ->orwhere('log_info', 'like', '%'.$mark.'%')
                ->latest('log_time')
                ->paginate(PAGE_NUM);
                $url=url('admin/logs');
                $logs->withPath($url.'?table_search='.$mark);
        }else{
            $logs = DB::table('admin_logs')
                ->join('admin_users','admin_logs.admin_id','=','admin_users.id')
                ->latest('log_time')
                ->paginate(PAGE_NUM);
        }
        $now = Carbon::now();
        $dt = Carbon::parse($now);
        $month = $dt->month; //当前月
        $needelMonth = $month-3;
        DB::table('admin_logs')->whereMonth('log_time',$needelMonth)->delete();
        return view('admin.admin.logs', compact('logs','mark'));
    }
}
